package cn.chenxing.module.query.service;

import cn.chenxing.domain.dto.TrackPoint;
import cn.chenxing.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

/**
 * @Description 查询服务端
 * @Author maogen.ymg
 * @Date 2020/4/14 23:47
 */
@Slf4j
@Service
public class QueryService {
    /**百度地图密钥**/
    private String AK = "FbLNjND6c4fmRclozbxNlkHXzi5THXFK";

    /**
     * 调用百度地图API根据地址，获取坐标
     * @param address 地址
     * @return 坐标
     */
    public TrackPoint getCoordinate(String address) {
        if (address != null && !"".equals(address)) {
            address = address.replaceAll("\\s*", "").replace("#", "栋");
            String url = "http://api.map.baidu.com/geocoding/v3/?address=" + address
                    + "&output=json&ak=" + AK + "&callback=showLocation";
            String json = loadJson(url);
            if (!"".equals(json)) {
                json = json.replace("showLocation&&showLocation(", "").replace(")","");
                JSONObject obj = JSONObject.fromObject(json);
                // 响应成功
                if ("0".equals(obj.getString("status"))) {
                    // 经度
                    double longitude = obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
                    // 纬度
                    double latitude = obj.getJSONObject("result").getJSONObject("location").getDouble("lat");

                    TrackPoint trackPoint = new TrackPoint();
                    trackPoint.setLongitude(CommonUtil.decimalValue(longitude, 5));
                    trackPoint.setLatitude(CommonUtil.decimalValue(latitude, 5));
                    return trackPoint;
                }else {
                    log.error("请求逆编码服务失败，原因为：{}", obj.getString("message"));
                }
            }
        }
        return null;
    }

    /**
     * 用过URL加载Json
     * @param url URL
     * @return Json
     */
    private String loadJson(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection uc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), StandardCharsets.UTF_8));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
            log.error("获取响应字符串失败，原因为：{}", e.getLocalizedMessage(), e);
        }
        return json.toString();
    }
}

